package cn.exrick.xboot.modules.news.controller;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.FileUtile;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.news.dao.mapper.NewsImagesMapper;
import cn.exrick.xboot.modules.news.entity.NewsImages;
import cn.exrick.xboot.modules.news.entity.news;
import cn.exrick.xboot.modules.news.service.INewsImagesService;
import cn.exrick.xboot.modules.news.service.InewsService;
import cn.exrick.xboot.modules.news.utils.newsUtil;
import cn.exrick.xboot.modules.portalConfig.service.IPortalConfigService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Exrick
 */
@Slf4j
@RestController
@Api(description = "测试管理接口")
@RequestMapping("/xboot/news")
@Transactional
public class newsController {

    @Autowired
    private InewsService inewsService;


    @Autowired
    private INewsImagesService iNewsImagesService;
    @Autowired
    private IPortalConfigService iPortalConfigService;


    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<news> get(@PathVariable String id) {
        news news = inewsService.getById(id);
        return new ResultUtil<news>().setData(news);
    }

    @RequestMapping(value = "/getNewsById", method = RequestMethod.GET)
    @ApiOperation(value = "portal通过id获取")
    public Result<news> getNewsById(@Param("id") String id) {
        news news = inewsService.getById(id);
        return new ResultUtil<news>().setData(news);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public Result<List<news>> getAll() {

        List<news> list = inewsService.list();
        return new ResultUtil<List<news>>().setData(list);
    }
    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取")
    public Result<IPage<news>> getByPage(@ModelAttribute PageVo page) {

        IPage<news> data = inewsService.page(PageUtil.initMpPage(page));
        return new ResultUtil<IPage<news>>().setData(data);
    }

    @RequestMapping(value = "/getNewsByPage", method = RequestMethod.GET)
    @ApiOperation(value = "管理端分页获取新闻")
    public Result<IPage<news>> getNewsByPage(@ModelAttribute Page page,news n,@ApiParam("是否开始数据权限过滤") @RequestParam(required = false, defaultValue = "true") Boolean openDataFilter) {

        IPage<news> data = inewsService.selectNewsvoDictPage(page,n,openDataFilter);
        return new ResultUtil<IPage<news>>().setData(data);
    }

    @RequestMapping(value = "/getPortalNewsByPage", method = RequestMethod.GET)
    @ApiOperation(value = "portal分页获取新闻并返回单点地址")
    public Result<IPage<news>> getPortalNewsByPage(@ModelAttribute Page page,news n) {

        IPage<news> data = inewsService.selectPortalNewsvoDictPage(page,n);
        return new ResultUtil<IPage<news>>().setData(data);
    }
    @RequestMapping(value = "/getAPPNewsByPage", method = RequestMethod.GET)
    @ApiOperation(value = "APP分页获取新闻")
    public Result<IPage<news>> getAPPNewsByPage(@ModelAttribute Page page,news n) {

        IPage<news> data = inewsService.selectAPPNewsvoDictPage(page,n);
        return new ResultUtil<IPage<news>>().setData(data);
    }


    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "编辑或更新数据")
    public Result<news> saveOrUpdate(@ModelAttribute news news) {

        if (news.getNewsIsTop() == 0) {
            news.setNewsRate(0);//将当前新闻设置文置顶新闻
            //newsUtil.topIsOne();
            List<news> newlist = inewsService.selectNewsByTop("0");
            System.out.println("有" + newlist + "条置顶数据");
            for (news n : newlist) {
                //将置顶标记修改为否
                n.setNewsIsTop(1);
                n.setNewsRate(CommonConstant.NewsRate);//将原来置顶的新闻修改成默认排序等级
                inewsService.saveOrUpdate(n);
            }
        }
        news.setUpdateTime(new Date());
        log.info("更新新闻数据");
        if (inewsService.saveOrUpdate(news)) {
            return new ResultUtil<news>().setData(news);
        }
        return new ResultUtil<news>().setErrorMsg("操作失败");
    }


    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delAllByIds(@PathVariable String[] ids) {
        System.out.println("调用删除新闻方法");
        for (String id : ids) {
            inewsService.removeById(id);
        }
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }

    //njp add begin
    @RequestMapping(value = "/addNews", method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public Result<Object> addNews(@ModelAttribute news n) {
        //添加本地默认信息
        n.setInfoCode(CommonConstant.BDinfoCode);
        n.setSource(CommonConstant.SOURCE);

        if (n.getNewsIsTop() == 0) {
            n.setNewsRate(0);//将当前新闻设置文置顶新闻
            List<news> newlist = inewsService.selectNewsByTop("0");
            System.out.println("有" + newlist + "条置顶数据");
            for (news myn : newlist) {
                //将置顶标记修改为否
                myn.setNewsIsTop(1);
                myn.setNewsRate(CommonConstant.NewsRate);//将原来置顶的新闻修改成默认排序等级
                inewsService.saveOrUpdate(myn);
            }
        }
        n.setCreateTime(new Date());
        n.setUpdateTime(new Date());
        boolean flag = inewsService.save(n);
        String newsId = n.getId();
        String imageId = n.getImageId();
        System.out.println(imageId + "图片id");
        //20190722 njp 修改判断条件
        if (imageId != null && !imageId.equals("") && imageId.length() != 0 && !imageId.trim().isEmpty()) {
            log.info("开始将新闻id存储进图片表");
            //njp 20190717将新闻表的id存进图片表中保存 begin
            NewsImages newsImages = new NewsImages();
            newsImages.setNewsId(newsId);
            newsImages.setId(imageId);
            iNewsImagesService.saveOrUpdate(newsImages);
            //njp 20190717将新闻表的id存进图片表中保存 end
        }

        return new ResultUtil<Object>().setSuccessMsg("添加成功");
    }
    //njp add end


    //njp  20190716 图片上传begin
    @RequestMapping(value = "/newUpload", method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public Result<Object> upload(@RequestParam(required = false) MultipartFile file,
                                 @RequestParam(required = false) String base64,
                                 HttpServletRequest request) {


        String message;
        InputStream inputStream;
        //写入静态资源成功时报标识符
        boolean flag = false;
        String newId = null;
        System.out.println("新闻文件上传");

        //文件名称
        String fileName = file.getOriginalFilename();
        System.out.println("文件名字：" + fileName);

        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("文件后缀：" + suffix);
        /***************文件处理*********************/
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取上传地址
        String path= iPortalConfigService.selectPortalConfigByKey("upload").getValue();
        File uploadPath = new File(path);
        if (!uploadPath.exists()) {
            //创建目录
            uploadPath.mkdir();
        }
        // 新文件名（唯一）
        String newFileName = new Date().getTime() + "." + suffix;
        System.out.println("新文件名：" + newFileName);
        // 调用FileItem的write()方法，写入文件
        File newFile = new File(path + newFileName);

        //将图片存入文件夹
        File targetFile = new File(uploadPath, newFileName);
        try {
            file.transferTo(targetFile);
            message = "图片上传成功";
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
            message = "图片上传失败";
        }
        log.info(message);
        //成功写入后将资源地址保存到数据库中
        if (flag) {
            NewsImages newsImages = new NewsImages();
            //20190716以后要将这个地址变成活数据，现在拟计划是存储在properties配置文件中
            newsImages.setImagePath(path);
            newsImages.setCreateTime(new Date());
            newsImages.setOldName(fileName);
            newsImages.setName(newFileName);
            //newsImages.setNewsId("789798797987979797");//测试
            boolean save = iNewsImagesService.save(newsImages);
            if (save) {
                newId = newsImages.getId();
                log.info(newsImages.getId() + "新存进图片去的id");
            }
            return new ResultUtil<Object>().setData(newsImages);
        }
        return new ResultUtil<Object>().setErrorMsg("上传失败");
    }
    //njp  20190716 图片上传end


    /**
     * add 新闻主图的修改
     *
     * @param file
     * @param base64
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/editUpload", method = RequestMethod.POST)
    @ApiOperation(value = "修改主图")
    public Result<Object> editUpload(@RequestParam(required = false) MultipartFile file,
                                     @RequestParam(required = false) String base64,
                                     HttpServletRequest request, @Param("id") String id) {

        System.out.println("测试获取id:" + id);
        log.info("开始上传修改主图");
        String message = null;
        //文件资源流
        InputStream inputStream;
        //写入静态资源成功时报标识符
        boolean flag = false;
        String newId = null;


        //1.将上传的图片存到服务器中
        //文件名称
        String fileName = file.getOriginalFilename();
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取上传地址
        //String path = request.getSession().getServletContext().getRealPath("/upload/");
        String path= iPortalConfigService.selectPortalConfigByKey("upload").getValue();
        //创建输出路径
        File uploadPath = new File(path);
        log.info("上传路径地址" + path);
        if (!uploadPath.exists()) {
            //创建目录
            uploadPath.mkdir();
        }
        // 新文件名（唯一）
        String newFileName = new Date().getTime() + "." + suffix;
        // 调用FileItem的write()方法，写入文件
        File newFile = new File(path + newFileName);
        File targetFile = new File(uploadPath, newFileName);
        try {
            file.transferTo(targetFile);
            message = "图片上传成功";
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
            message = "图片上传失败";
        }
        //2.根据新闻id查询原图片信息并通过该地址信息进行静态资源的删除
        NewsImages newsImages1 = iNewsImagesService.selectNewsImagesByNewsId(id);
        if(newsImages1!=null) {
            FileUtile.deleteServerFile(path, newsImages1.getName());
            //3.根据新闻id删除图片表(t_news_images)中的对应图片信息
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", id);
            boolean b = iNewsImagesService.deleteNewsImagesByNewsId(map);
        }
        //4.将新图片信息存进图片表中
        if (flag) {
            NewsImages newsImages = new NewsImages();
            newsImages.setNewsId(id);
            newsImages.setImagePath(path);
            newsImages.setCreateTime(new Date());
            newsImages.setOldName(fileName);
            newsImages.setName(newFileName);
            boolean save = iNewsImagesService.save(newsImages);
            if (save) {
                newId = newsImages.getId();
                log.info(newsImages.getId() + "新存进图片去的id");
            }
            return new ResultUtil<Object>().setData(newsImages);
        }
        return new ResultUtil<Object>().setErrorMsg("上传失败");
    }

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public Result<IPage<NewsImages>> test(@ModelAttribute Page page) {
       /* //String newId="797987987797887";
        NewsImages newsImages = new NewsImages();
        //20190716以后要将这个地址变成活数据，现在拟计划是存储在properties配置文件中
        newsImages.setId("163498775048884224");
        newsImages.setNewsId("163498775048884224");
        newsImages.setOldName("testnjp");
        newsImages.setNewsId("45646464");

        Page<NewsImages> page = new Page<>(1,10);

       // iNewsImagesService

        boolean b = iNewsImagesService.saveOrUpdate(newsImages);
        log.info(b+"是否成功插入");
        return new ResultUtil<Object>().setData(newsImages);*/
        //iNewsImagesService.se
        page.setSize(10);
        page.setCurrent(1);
        IPage<NewsImages> newsImagesIPage = iNewsImagesService.selectPageVo(page, "logo.png");

        return new ResultUtil<IPage<NewsImages>>().setData(newsImagesIPage);
        // return null;
    }


    public static void main(String[] args) {
        FileUtile.deleteServerFile("C:/Users/Asher/AppData/Local/Temp/tomcat-docbase.1863436851554026425.8888/upload/", "1564476639437.png");
        /*String substring = fileUrl.substring(beginIndex + 1, endIndex);*/

    }
}
